var Game = function () {
  var canvas = document.getElementById('canvas')
  var context = canvas.getContext('2d')

  var g = {
    canvas: canvas,
    context: context,

    // 按键注册机制
    actions: {},
    keydowns: {},
  }

  g.update = function () { }

  g.drawImage = function (imgObj) {
    g.context.drawImage(imgObj.img, imgObj.x, imgObj.y)
  }

  g.drawRect = function (rect, fillStyle) {
    g.context.save()
    g.context.beginPath()
    g.context.fillStyle = fillStyle
    g.context.rect(rect.x, rect.y, rect.width, rect.height)
    g.context.closePath()
    g.context.fill()
    g.context.restore()
  }

  g.draw = function () { }

  g.addAction = function (key, callback) {
    g.actions[key] = callback;
  }

  window.addEventListener('keydown', function (event) {
    g.keydowns[event.key] = true;
  });

  window.addEventListener('keyup', function (event) {
    g.keydowns[event.key] = false;
  });


  g.runWithScene = function (scene) {
    g.update = function () {
      scene.update()
    }
    g.draw = function () {
      scene.draw()
    }
  }


  function drawFrame() {

    // update
    g.update()


    Object.keys(g.actions).forEach(function (key) {
      if (g.keydowns[key]) {
        // 如果按键被按下， 调用注册的函数
        g.actions[key]();
      }
    });
    // clear and draw

    context.clearRect(0, 0, canvas.width, canvas.height)

    g.draw()

    // requestAnimationFrame(drawFrame);
    let fps = window.fps || 60
    setTimeout(drawFrame, 1000 / fps)

  }

  drawFrame()


  return g
}
